package com.goodfox.web.generic.file.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.goodfox.web.generic.file.entity.FileEntity;
import com.goodfox.web.generic.file.entity.WebFormEntity;
import com.goodfox.web.generic.file.service.FileUploadService;
import com.goodfox.web.generic.provide.util.DateUtil;
import com.goodfox.web.generic.provide.util.TransformUtil;
import com.goodfox.web.generic.provide.util.UUIDUtil;

/**
 * FileUploadService接口实现类 
 * sundongkai第二版修改
 * @author qin gt
 *
 */
@Service("fileUploadService")
public class FileUploadServiceImpl implements FileUploadService {

	/** log4j日志器 */
	private Logger logger=Logger.getLogger(FileUploadServiceImpl.class);
	

	public WebFormEntity webFileUpload(HttpServletRequest request){
		return webFileUpload(request, true, true, true, null);
	}

	public WebFormEntity webFileUpload(HttpServletRequest request,boolean copyDisk,boolean changeByte,boolean openAccess,String folder){
		WebFormEntity webForm=new WebFormEntity();
		List<FileEntity> fileEntitys=new ArrayList<FileEntity>();
		Map<String,String> paraMap=new HashMap<String,String>();
		webForm.setFileUpSuccess(false);
		boolean multipart=ServletFileUpload.isMultipartContent(request);
		if(multipart){
			try{
				FileItemFactory factory=new DiskFileItemFactory();
				ServletFileUpload upload=new ServletFileUpload(factory);
				List<FileItem> items=upload.parseRequest(request);
				if(items!=null){
					Iterator<FileItem> iterator=items.iterator();
					while(iterator.hasNext()){
						FileItem item=(FileItem)iterator.next();
						if(!item.isFormField()){
							FileEntity fileEntity = new FileEntity();
							String webInf="";
							if(!openAccess){
								webInf="WEB-INF";
							}
							String realPath=request.getSession().getServletContext().getRealPath(webInf).replace("\\", "/")+"/";
							String folderPath="/default";
							if(folder!=null && !folder.trim().equals("")){
								folderPath=folder.trim();
							}
							String newPath="/fileUpload/"+folderPath+"/"+DateUtil.format(new Date(), "yyyyMMdd")+"/";
							String origPath=item.getName();
							fileEntity.setCtrlName(item.getFieldName());
							fileEntity.setExteName(origPath.substring(origPath.lastIndexOf(".") + 1,origPath.length()));
							fileEntity.setOrigName(origPath.substring(origPath.lastIndexOf("/") + 1,origPath.length()));
							fileEntity.setNewName(UUIDUtil.getUUID()+"."+fileEntity.getExteName());
							fileEntity.setShowPath(newPath+fileEntity.getNewName());
							fileEntity.setRealPath(realPath+fileEntity.getShowPath());
							if(copyDisk){
								//创建文件夹
								File newFolder = new File(realPath+newPath);
								if (!newFolder.exists()) {
									newFolder.mkdirs();
								}
								//创建写入文件
								File newFile = new File(fileEntity.getRealPath());
								if (!newFile.exists()) {
									newFile.createNewFile();
								}
								//向服务器写入文件
								BufferedInputStream input = new BufferedInputStream(item.getInputStream()); 
								BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(fileEntity.getRealPath()));
								try{
									byte[] buffer = new byte[1024];
									int size = 0;
									while (-1 != (size = input.read(buffer, 0, 1024))) {
										output.write(buffer, 0, size);
										output.flush();
									}
								}catch(Exception ex){ 
									logger.error("写入文件内容异常",ex);
								}finally{
									if(input != null){
										input.close();
									}
									if(output != null){
										output.close();
									}
								}
							}
							if(changeByte){
								fileEntity.setByteFile(TransformUtil.stream2Bytes(item.getInputStream()));
							}
							fileEntitys.add(fileEntity);
						}else{
							paraMap.put(item.getFieldName().trim(), item.getString("utf-8").trim());
						}
					}
					paraMap.remove("Filename");
					paraMap.remove("fileext");
					paraMap.remove("Upload");
					paraMap.remove("folder");
					webForm.setFileEntitys(fileEntitys);
					webForm.setParaMap(paraMap);
				}
				webForm.setFileUpSuccess(true);
			}catch(FileUploadException fuex){
				logger.error("文件解析异常",fuex);
			}catch(UnsupportedEncodingException ueex){
				logger.error("获取表单参数异常",ueex);
			}catch(IOException ioex){
				logger.error("文件流操作异常",ioex);
			}catch(Exception ex){ 
				logger.error("上传文件异常",ex);
			}
		}
		return webForm;
	}
	
}
